<script lang="ts" setup>
import { ref, watch } from "vue"
import plyr from "@cop/plyr/index.vue"
import { NButton, NTag, NSpin, NEllipsis, NDivider, NEmpty } from "naive-ui"
import { getVideoDetail } from "@/api"
import { plyrInstance } from "@/hooks/usePlyr"
import { videoId } from "@/hooks/useVideoId"
import { setStorage, getStorage } from "@/util/cache"
import { isHistoryMode } from "@/hooks/useHistoryMode"
import atropos from "@cop/atropos/index.vue"
import req from "@/http"
const plyrRef = ref<typeof plyr>()
const videoDetail = ref({})
const videoList = ref([])
const storageKey = "watch_video_history"
const current = ref<number>(0)
const videoUrl = ref("")
const iframeUrl = ref("")
const iframeRef = ref()
const baseUrl = `https://43.240.156.118:8443/vip/?url=`
const cacheList = ref([])

const isLoadding = ref(false)

watch(
  isHistoryMode,
  val => {
    try {
      cacheList.value =
        JSON.parse(getStorage(storageKey)) === null ? [] : JSON.parse(getStorage(storageKey))
      console.log("cacheList", cacheList.value)
    } catch (error) {
      cacheList.value = []
    }
  },
  {
    immediate: true,
  }
)

const cacheVideoInfo = () => {
  try {
    const originData = JSON.parse(getStorage(storageKey))
    if (originData.some(item => item.id == videoId.value)) {
      const data = originData.map(item2 => {
        if (item2.id == videoId.value) {
          return {
            ...item2,
            current: current.value,
          }
        } else {
          return item2
        }
      })
      setStorage(storageKey, JSON.stringify(data))
    } else {
      originData.push({
        id: videoId.value,
        current: current.value,
        info: videoDetail.value,
      })
      setStorage(storageKey, JSON.stringify(originData))
    }
  } catch (error) {
    setStorage(
      storageKey,
      JSON.stringify([
        {
          id: videoId.value,
          current: current.value,
          info: videoDetail.value,
        },
      ])
    )
  }
}
const initCurrent = (videoId: string) => {
  try {
    const list = JSON.parse(getStorage(storageKey))
    const data = list.filter(item => item.id == videoId)
    current.value = data && data.length > 0 ? data[0].current : 0
  } catch (error) {}
}

watch(videoId, val => {
  console.log("val", val)
  initCurrent(val)
  getVideoData(val)
})

const getVideoData = val => {
  // document.cookie = "cleanMode=0; fikker-ZoOO-TARI=TU6LBaZGOMT1OIDQjoH7XiZm4slMhsJN"
  // fetch("https://api.agedm.org/v2/detail/20210185", {
  //   headers: {
  //     Cookie: "cleanMode=0; fikker-ZoOO-TARI=TU6LBaZGOMT1OIDQjoH7XiZm4slMhsJN",
  //   },
  // })
  isLoadding.value = true
  getVideoDetail(val)
    .then(res => {
      console.log("res", res)
      videoDetail.value = res
      cacheVideoInfo()
      videoList.value = videoDetail.value.video.playlists.qq
        ? videoDetail.value.video.playlists.qq
        : videoDetail.value.video.playlists[Object.keys(videoDetail.value.video.playlists)[0]]
      console.log("videoList=", videoList.value)

      iframeUrl.value = baseUrl + videoList.value[current.value][1]
      isLoadding.value = false
      isHistoryMode.value = false
      // console.log(videoDetail.value.video.playlists.qq)
    })
    .catch(err => {
      isLoadding.value = false
    })
}

// const getVideoUrl = (url: string) => {
// return new Promise((resolve, reject) => {
//   const iframeEl = document.createElement("iframe")
//   iframeEl.src = baseUrl + url
//   console.log("getVideoUrl")
//   iframeEl.onload = () => {
//     console.dir(iframeEl)
//     resolve(iframeEl)
//   }
// })
// }

const iframeLoaded = () => {
  if (iframeUrl.value == "") return
  console.dir(iframeRef.value)
}

const changeVideo = async (item, index) => {
  current.value = index
  cacheVideoInfo()
  iframeUrl.value = baseUrl + item[1]
  const { res, err, isSuccess } = await req({
    method: "get",
    url: "/v2/detail/20210185",
    // params: query
  })
  return isSuccess ? res : err

  // console.log(item)
  // const videoUrl =
  // console.log("videoUrl", videoUrl)
}
const goVideoDetail = id => {
  if (videoId.value == id) {
    isHistoryMode.value = false
    return
  }
  videoId.value = id
}
const prev = () => {
  if (current.value == 0) return
  current.value = current.value - 1
  cacheVideoInfo()
  iframeUrl.value = baseUrl + videoList.value[current.value][1]
}
const next = () => {
  if (current.value == videoList.value.length - 1) return
  current.value = current.value + 1
  cacheVideoInfo()
  iframeUrl.value = baseUrl + videoList.value[current.value][1]
}
</script>

<template>
  <div
    style="display: flex; align-items: center; justify-content: center; margin-top: 20px"
    v-if="isLoadding"
  >
    <n-spin size="small" :show="isLoadding" />
  </div>
  <div class="content" v-if="!isHistoryMode">
    <!-- <plyr ref="plyrRef" :src="videoUrl" /> -->
    <div class="top">
      <iframe
        :src="iframeUrl"
        frameborder="0"
        @load="iframeLoaded"
        ref="iframeRef"
        allowfullscreen
        scrolling="no"
        allowtransparency
      ></iframe>
      <div class="action">
        <div class="name">
          <n-ellipsis :line-clamp="2">
            {{ videoDetail.video && videoDetail.video.name }} - 共{{ videoList.length }}集
          </n-ellipsis>
        </div>
        <div class="btns">
          <n-button type="primary" @click="prev">上一集</n-button>
          <n-button type="primary" @click="next">下一集</n-button>
        </div>
      </div>
    </div>

    <div class="list">
      <div class="item" v-for="(item, index) in videoList" :key="index">
        <n-tag :type="index == current ? 'error' : 'info'" @click="changeVideo(item, index)">
          第{{ index + 1 }}集
        </n-tag>
      </div>
    </div>
  </div>
  <template v-else-if="isHistoryMode">
    <n-divider title-placement="center">观看历史</n-divider>
    <n-empty description="暂无观看历史,快去搜索影片观看吧～" v-if="!cacheList.length"> </n-empty>
    <div class="cache-list">
      <atropos :suffix="item.id.toString()" v-for="item in cacheList" :key="item.id">
        <div class="cache-item my-button" @click="goVideoDetail(item.id)">
          <div class="cover-box">
            <img :src="item.info.video.cover" class="cover" />
          </div>
          <div class="video-info">
            <div class="video-name">{{ item.info.video.name }}</div>
            <div class="normal-info-block">
              <div class="normal-info-item">
                <div class="normal-info-item-title">总计集数：</div>
                <div class="normal-info-item-content">
                  {{ item.info.video.uptodate.replace("第", "共") }}
                </div>
              </div>
              <div class="normal-info-item">
                <div class="normal-info-item-title">上次看到：</div>
                <div class="normal-info-item-content">第{{ item.current + 1 }}集</div>
              </div>
              <div class="normal-info-item">
                <div class="normal-info-item-title">影片状态：</div>
                <div class="normal-info-item-content">
                  <n-tag :type="item.info.video.status == '连载' ? 'info' : 'success'">
                    {{ item.info.video.status }}</n-tag
                  >
                </div>
              </div>
              <div class="normal-info-item">
                <div class="normal-info-item-title">影片年份：</div>
                <div class="normal-info-item-content">{{ item.info.video.year }} 年</div>
              </div>
              <div class="normal-info-item">
                <div class="normal-info-item-title">播放热度：</div>
                <div class="normal-info-item-content">{{ item.info.video.rank_cnt }}</div>
              </div>
            </div>
          </div>
        </div>
      </atropos>
    </div>
  </template>
</template>

<style lang="scss" scoped>
.cache-list {
  box-sizing: border-box;
  padding-left: 10px;
  padding-right: 10px;
  padding: 10px;
  height: 90%;
  overflow-y: scroll;
  @media only screen and (max-width: 767px) {
    /* 在宽度小于等于 767px 的设备上应用以下样式 */
    display: block;
  }

  /* 桌面设备样式 */
  @media only screen and (min-width: 1024px) {
    /* 在宽度大于等于 1024px 的设备上应用以下样式 */

    display: flex;
    flex-wrap: wrap;
    gap: 30px;
    margin-top: 20px;
    align-items: flex-start;
  }
  .cache-item {
    display: flex;
    gap: 10px;
    height: 220px;
    margin-bottom: 30px;
    cursor: pointer;
    box-sizing: border-box;
    border-radius: 10px;
    background-color: var(--login-tip-bg);
    border: 1px solid var(--login-tip-border-color);
    transition: all 0.3s var(--n-bezier);
    padding: 10px;

    @media only screen and (max-width: 767px) {
      /* 在宽度小于等于 767px 的设备上应用以下样式 */
      margin: 0 auto;
      margin-bottom: 20px;
      width: 90%;
    }
    @media only screen and (min-width: 1024px) {
      /* 在宽度大于等于 1024px 的设备上应用以下样式 */
      margin-left: 28px;
      width: 340px;
    }
    .cover-box {
      width: 160px;
      height: 100%;
      flex-shrink: 0;
      .cover {
        width: 100%;
        height: 100%;
        border-radius: 6px;
      }
    }
    .video-info {
      flex: 1;
      .video-name {
        color: var(--TextColor);
        font-size: 16px;
        transition: color 0.3s var(--n-bezier);
        margin-bottom: 8px;
      }
      .normal-info-block {
        .normal-info-item {
          display: flex;
          align-items: center;
          margin-bottom: 5px;
          .normal-info-item-title {
            width: 75px;
            flex-shrink: 0;
            color: #999;
          }
          .normal-info-item-content {
            flex: 1;
            transition: color 0.3s var(--n-bezier);
            color: var(--TextColor);
          }
        }
      }
    }
  }
}
.content {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 10px;
  overflow: hidden;

  .action {
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    .name {
      font-size: 20px;
      color: var(--TextColor);
      transition: all 0.3s var(--n-bezier);
    }
    .btns {
      display: flex;
      align-items: center;
      // justify-content:;
      gap: 20px;
    }
  }

  .top {
    height: 53%;
    iframe {
      width: 100%;
      height: 300px;
    }
  }

  .list {
    height: 43%;
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    margin-top: 20px;
    overflow-y: scroll;
    .item {
      width: 70px;
      text-align: center;
    }
  }
}
</style>
